package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {

    /**
     * 网关全局过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 1.是否为登录请求
        if (request.getURI().getPath().contains("/login")) {
            // 1.1放行
            return chain.filter(exchange);
        }

        // 2.是否携带token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            // 不携带，返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            // 3.token是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            // 获取过期判断
            int validVal = AppJwtUtil.verifyToken(claimsBody);
            // 3.1token是否过期
            if (validVal == 1 || validVal == 2) {
                // 3.1.1已过期，返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            // 3.2解析token错误，返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 4.放行
        return chain.filter(exchange);
    }


    /**
     * 过滤器优先级设置
     * @return 值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
